// index.js
const config = require('../../config/index')

Page({
  data: {
    idcardFrontSide: true,
    cameraContext: null,
    type: '',
    baseUrl: config.baseUrl, 
    theme: wx.getStorageSync('InvoiceLoanTheme') || ''
  },

  onLoad(options) {
    // 创建camera上下文
    this.setData({
      cameraContext: wx.createCameraContext(),
      idcardFrontSide: options.type === 'idCardPicFront',
      type: options.type,
      theme: wx.getStorageSync('InvoiceLoanTheme') || ''
    });
  },

  // 拍照
  takePhoto() {
    const that = this
    this.data.cameraContext.takePhoto({
      quality: 'normal',
      success: (res) => {
        wx.showLoading({
          title: '图片上传中',
          mask: true
        })
        const token = wx.getStorageSync('InvoiceLoanToken')
        const { type } = that.data
        wx.uploadFile({
          filePath: res.tempImagePath,
          name: 'file',
          header:{
            Authorization: token,
            'Content-Type': 'multipart/form-data',
          },
          url: `${config.baseUrl}/ocr/id/card`,
          formData:{
            field: type
          },
          success(uploadRes){
            wx.hideLoading()
            const data = JSON.parse(uploadRes.data)
            if(data.code === 200) {
              const formData = {}
              let aa = data.data[type==='idCardPicFront'?'idCardNo':'effPeriod']
              if(type!=='idCardPicFront'){
                let startDate = ''
                let endDate = ''
                const arr = aa.split('-')
                startDate = arr[0].replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3")
                endDate = arr[1].replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3")
                aa = `${startDate}-${endDate}`
              } else {
                formData.userName = data.data.userName
              }
              const pages = getCurrentPages();
              const prevPage = pages[pages.length - 2];
              prevPage.setData({
                [type]: res.tempImagePath,
                formData: {
                  ...prevPage.data.formData,
                  ...formData,
                  [type==='idCardPicFront'?'idCard':'validityPeriod']: aa,
                }
              });
              wx.navigateBack()
            } else {
              wx.showToast({
                title: data.message,
                icon:'none'
              })
            }
          }
        })
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({
          title: '拍照失败，请检查系统是否授权',
          icon: 'none',
          duration: 1200
        });
      }
    });
  },
});